<template>
    <div class="frame0">    
        <table class="frame">   
            <thead>
            <tr>
                <th>编号</th><th>游戏名</th><th>售价</th><th>操作</th>
            </tr>
        </thead>
        <tbody v-if="gamelist.length!=0">
            <tr v-for="(item,index) in gamelist" :key="index">
                <td>{{ index+1 }}</td><td>{{ item.name }}</td>
                <td :class="{low:item.sale<60,hight:item.sale>=60}">{{ item.sale }}</td><td><a href="#" @click="del(item.name,index)">删除</a></td>
            </tr>
        </tbody>
        <tfoot>
            <tr class="foot" v-if="gamelist.length!=0">
                <td colspan="2" style="border-right: solid grey 1px;">总数为:{{ all }}</td>
                <td colspan="2">平均为:{{ Average }}</td>
            </tr>
            <tr>
                <td class="none" colspan="4" v-if="gamelist.length==0">
                    暂无游戏
                </td>
            </tr>
        </tfoot>
    </table>
    </div>
    <div>
        <div class="subject1"><span class="subject">游戏:</span>
            <input type="text" v-model.trim="newobj.name" placeholder="请输入游戏" @keydown.enter="addone()">
        </div>
        <div class="subject1"><span class="subject">售价:</span>
            <input type="text" v-model.number="newobj.sale" placeholder="请输入售价" @keydown.enter="addone()">
        </div>
        <a href="#" @click="addone()" class="None"><div class="add"><span>添加</span></div></a>
    </div>
</template>

<script setup>
    import './App05.css'
    import { computed, onMounted, reactive, ref, watch} from 'vue';
    let gamelist=reactive(JSON.parse(localStorage.getItem("keygame1"))||[
        {id:12,name:"法环",sale:92},
        {id:13,name:"黑魂",sale:50},
        {id:14,name:"只狼",sale:91}
    ]);
    let all=computed(()=>{
        return gamelist.reduce((prev,item)=>prev+item.sale,0);
    })
    let Average=computed(()=>{
        return gamelist.length==0?0:Math.round(all.value/gamelist.length);
    })
    let newobj=reactive({
        name:"",
        sale:""
    })
    let addone=()=>{
        if(newobj.name.length==0)
        {
            return alert("游戏名不能为空")
        }
        if(newobj.sale.length==0)
        {
            return alert("售价不能为空")
        }
        if(typeof newobj.sale != 'number')
        {
            newobj.sale="";
            return alert("售价请输入数字")
        }
        gamelist.push({...newobj,id:Date.now()})
        newobj.name=newobj.sale="";
    }
    let del=(name,index)=>
    {
        if(window.confirm('你确定删除'+name+'吗?'))
        {
            gamelist.splice(index,1);
        }
    }
    watch(gamelist,(newval)=>{
        localStorage.setItem("keygame1",JSON.stringify(newval));
    },
    {
        deep:true
    })
</script>